package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.view.View;

import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.databinding.QrCodeActivityBinding;
import com.sgb.capital.model.QRcodeEntity;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.viewmodel.QrCodeModel;

import java.util.HashMap;
import java.util.Map;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

/**
 * 作者:张磊
 * 日期:2021/3/12 0012
 * 说明:资金中心1.3.9 二维码支付
 */


public class QrCodeActivity extends BaseActivity {

    QrCodeModel mModel;
    private QrCodeActivityBinding mBinding;
    private QRcodeEntity mQRcodeEntity;
    private CountDownTimer mTimer;
    private String mTradeNo;
    private boolean mIsPay;


    @Override
    public void initObserve() {
        mModel.mQRcodeEntityMutableLiveData.observe(this, qRcodeEntity -> receiveQRcode(qRcodeEntity));
    }

    /**
     * 参数json
     * QRcodeEntity  entity = new QRcodeEntity() ;
     * entity.amount="xxx";
     * ...
     * json =  new Gson().toJson(entity);
     *
     * @param context
     * @param json
     */
    public static void start(Context context, String json) {
        Intent intent = new Intent(context, QrCodeActivity.class);
        intent.putExtra("json", json);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.qr_code_activity);
        mModel = new ViewModelProvider(this).get(QrCodeModel.class);
    }

    public void initListener() {
        mBinding.ivBack.setOnClickListener(v -> {
            if (mTimer != null) {
                mTradeNo = null;
                mTimer.cancel();
                finish();
            }
        });
        mBinding.ivBack.setOnClickListener(v -> finish());
        // 点击切换支付方式
        mBinding.llBtnWx.setOnClickListener(v -> {
            if (mQRcodeEntity.payType.contains("WX")) return;
            getCut(0);
        });
        mBinding.llBtnAl.setOnClickListener(v -> {
            if (mQRcodeEntity.payType.contains("AL")) return;
            getCut(1);
        });
        // 点击刷新二维码
        mBinding.flOvertime.setOnClickListener(v -> {
            mBinding.flOvertime.setVisibility(View.GONE);
            mModel.receiveQRcode(this, mQRcodeEntity);
        });
    }

    private void getCut(int code) {
        if (mIsPay) {
            return;
        }
        mBinding.tvWx.setTypeface(code == 0 ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
        mBinding.tvAl.setTypeface(code == 0 ? Typeface.DEFAULT : Typeface.DEFAULT_BOLD);
        mBinding.tvWx.setTextColor(Utils.getColor(code==0?R.color.color_ef4033:R.color.color_333333));
        mBinding.tvAl.setTextColor(Utils.getColor(code==0?R.color.color_333333:R.color.color_ef4033));
        mBinding.ivIcon.setImageResource(code == 0 ? R.mipmap.wx_icon : R.mipmap.al_icon);
        mBinding.tvTip.setText(code == 0 ? "请使用微信扫一扫，扫描二维码支付" : "请使用支付宝扫一扫，扫描二维码支付");
        mBinding.vWx.setVisibility(code == 0 ? View.VISIBLE : View.INVISIBLE);
        mBinding.vAl.setVisibility(code == 0 ? View.INVISIBLE : View.VISIBLE);
        mQRcodeEntity.payType = code == 0 ? "WX" : "AL";
        mBinding.flOvertime.setVisibility(View.GONE);
        mModel.receiveQRcode(this, mQRcodeEntity);
    }

    public void initData() {
        mTimer = new CountDownTimer(60000 * 5, 2000) {
            public void onTick(long millisUntilFinished) {
                if (!Utils.isEmpty(mTradeNo) && !mIsPay) {
                    mModel.queryPayState(QrCodeActivity.this, mTradeNo);
                }
            }

            public void onFinish() {
                mTimer.cancel();
                mBinding.flOvertime.setVisibility(View.VISIBLE);
            }
        };

        String json = getIntent().getStringExtra("json");
        if (!Utils.isEmpty(json)) {
            mQRcodeEntity = new Gson().fromJson(json, QRcodeEntity.class);
            mBinding.tvMoney.setText("￥" + Utils.getDecimalFormat(Float.parseFloat(mQRcodeEntity.amount)));
            getCut(mQRcodeEntity.payType.contains("WX") ? 0 : 1);
            mModel.receiveQRcode(this, mQRcodeEntity);
            return;
        }
    }

    // 生成二维码并刷新UI
    public void receiveQRcode(QRcodeEntity data) {
        mBinding.flQr.setVisibility(View.VISIBLE);
        mBinding.tvMoney.setText("￥\t" + mQRcodeEntity.amount);
        mTradeNo = data.tradeNo;
        mBinding.ivQr.setImageBitmap(createQRCode(data.paymentLink));
        mTimer.start();
    }

    private Bitmap createQRCode(String s) {
        int width = 600;
        int height = 600;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix encode = null;
        try {
            encode = qrCodeWriter.encode(s, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int[] colors = new int[width * height];
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                if (encode.get(i, j)) {
                    colors[i * width + j] = Color.BLACK;
                } else {
                    colors[i * width + j] = Color.WHITE;
                }
            }
        }
        return Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.onFinish();
        }
    }


    // 轮询查询交易是否支付完成
    public void queryPayState(boolean data) {
        mIsPay = data;
        if (data) {
            mBinding.llPaySuccess.setVisibility(View.VISIBLE);
            mBinding.tvMoneyTip.setText(mQRcodeEntity.amount);
            Utils.sendMsg(Constants.EVENT_REFRESH, null);
            mTimer.cancel();
        }
    }
}